package main

import (
	"fmt"
	"net/http"
	"html/template"
	"strings"
//	"io"
	"log"
)

func sayHelloName(w http.ResponseWriter,r *http.Request){
	r.ParseForm()//parse parameters
	fmt.Println("--------------------------------------------")
	fmt.Println(r.Form)
	fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
	for k,v:=range r.Form {
		fmt.Println("key: ",k)
		fmt.Println("val: ",strings.Join(v," "))
	}
	fmt.Fprintf(w, "Hello! Let's test cross site script.")
}

func form(w http.ResponseWriter,r *http.Request){
	fmt.Println("--------------------------------------------")
	fmt.Println("Request Method: ",r.Method)
	fmt.Println("Form data: ",r.Form)
	if r.Method=="GET" {
		t,_:=template.ParseFiles("cross_site.gtpl")
		t.Execute(w,nil)
	}else{
		r.ParseForm()
		
		t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
		err = t.ExecuteTemplate(w, "T", "<script>alert('you have been pwned')</script>")
//		err = t.ExecuteTemplate(out, "T", template.HTML("<script>alert('you have been pwned')</script>"))
//		err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
		fmt.Println("t.ExecuteTemplate error: ",err)
		
		fmt.Println("username: ",template.HTMLEscapeString(r.Form.Get("username")))
		fmt.Println("password: ",template.HTMLEscapeString(r.Form.Get("password")))
		fmt.Println("interest: ",template.HTMLEscapeString(r.Form.Get("interest")))
		fmt.Println("gender: ",template.HTMLEscapeString(r.Form.Get("gender")))
		fmt.Println("fruit: ",template.HTMLEscapeString(r.Form.Get("fruit")))

		fmt.Fprintf(w,"username: %v\n",template.HTMLEscapeString(r.Form.Get("username")))
		fmt.Fprintf(w,"password: %v\n",template.HTMLEscapeString(r.Form.Get("password")))
		fmt.Fprintf(w,"interest: %v\n",template.HTMLEscapeString(r.Form.Get("interest")))
		fmt.Fprintf(w,"gender:   %v\n",template.HTMLEscapeString(r.Form.Get("gender")))
		fmt.Fprintf(w,"fruit:    %v\n",template.HTMLEscapeString(r.Form.Get("fruit")))
	}
}

func main(){
	http.HandleFunc("/",sayHelloName)
	http.HandleFunc("/form",form)
	er:=http.ListenAndServe(":9090",nil)
	if er!=nil{
		log.Fatal("ListenAndServe",er)
	}
}